package com.SouthernWall_404.Age_Capitalism.common.Network.S2C;

import com.SouthernWall_404.Age_Capitalism.common.Init.ModBlocks;
import com.SouthernWall_404.Age_Capitalism.common.Network.ClientHandler.MerchantClientHandler;
import com.SouthernWall_404.Age_Capitalism.common.Network.ClientHandler.StoreBlockEntityHandler;
import com.SouthernWall_404.Age_Capitalism.common.World.Blocks.StoreBlock;
import com.SouthernWall_404.Age_Capitalism.common.World.Entity.StoreBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.item.trading.MerchantOffers;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public class StoreBlockEntityPacket {

    public StoreBlockEntity blockEntity;
    public int windowId;
    public BlockPos blockPos;

    public CompoundTag data;


    public StoreBlockEntityPacket(StoreBlockEntity blockEntity, int windowId) {

        this.blockEntity=blockEntity;
        this.blockPos=blockEntity.getBlockPos();
        this.windowId=windowId;
    }

    public StoreBlockEntityPacket(FriendlyByteBuf p_178985_) {


        this.windowId=p_178985_.readInt();
        this.blockPos=p_178985_.readBlockPos();
        CompoundTag entityInfo=p_178985_.readNbt();

        this.blockEntity=new StoreBlockEntity(this.blockPos,ModBlocks.STORE_BLOCK.get().defaultBlockState());
        if(!entityInfo.isEmpty())
        {
            this.blockEntity.load(entityInfo);
        }




    }

    public void encode(FriendlyByteBuf p_132470_) {



        p_132470_.writeInt(this.windowId);
        p_132470_.writeBlockPos(this.blockPos);
        CompoundTag entityInfo=this.blockEntity.getUpdateTag();
        p_132470_.writeNbt(entityInfo);

    }

    public void handle(Supplier<NetworkEvent.Context> ctx)
    {
        ctx.get().enqueueWork(() ->
                // 确保其仅在物理客户端上执行
                DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> StoreBlockEntityHandler.handleOpenPacket(this,ctx))
        );
        ctx.get().setPacketHandled(true);
    }
}
